<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高精度位置获取</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .btn-high-precision {
            background-color: #28a745;
        }
        .btn-high-precision:hover {
            background-color: #218838;
        }
        .info {
            margin-top: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 5px;
            display: none;
        }
        .error {
            color: #dc3545;
            background-color: #f8d7da;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .success {
            color: #155724;
            background-color: #d4edda;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .coordinates {
            font-family: monospace;
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .accuracy-indicator {
            padding: 5px 10px;
            border-radius: 15px;
            color: white;
            font-size: 12px;
            margin-left: 10px;
        }
        .accuracy-high { background-color: #28a745; }
        .accuracy-medium { background-color: #ffc107; color: black; }
        .accuracy-low { background-color: #dc3545; }
        .tips {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>高精度位置获取</h1>

    <div class="tips">
        <strong>提高精度提示：</strong>
        <ul>
            <li>在室外开阔地带使用GPS定位（精度可达5-10米）</li>
            <li>确保设备已开启位置服务和高精度模式</li>
            <li>使用HTTPS协议访问（localhost环境自动支持高精度）</li>
            <li>避免在建筑物密集区域使用网络定位</li>
        </ul>
    </div>

    <div>
        <button id="getLocationBtn">标准精度定位</button>
        <button id="getHighPrecisionBtn" class="btn-high-precision">高精度定位</button>
        <button id="watchLocationBtn">持续定位监控</button>
    </div>

    <div id="error" class="error"></div>
    <div id="success" class="success"></div>

    <div id="locationInfo" class="info">
        <h3>位置信息: <span id="accuracyIndicator" class="accuracy-indicator"></span></h3>
        <div class="coordinates">
            <p><strong>纬度:</strong> <span id="latitude"></span></p>
            <p><strong>经度:</strong> <span id="longitude"></span></p>
            <p><strong>精度:</strong> <span id="accuracy"></span> 米</p>
            <p><strong>定位方式:</strong> <span id="positionSource"></span></p>
            <p><strong>海拔:</strong> <span id="altitude"></span> 米</p>
            <p><strong>时间戳:</strong> <span id="timestamp"></span></p>
        </div>

        <div id="mapContainer" style="margin-top: 20px;">
            <h4>地图位置:</h4>
            <div id="map" style="height: 300px; width: 100%; background-color: #e9ecef; border-radius: 5px; display: flex; align-items: center; justify-content: center;">
                <p>地图加载中...</p>
            </div>
        </div>
    </div>
</div>

<script>
    let watchId = null;

    document.getElementById('getLocationBtn').addEventListener('click', () => getLocation(false));
    document.getElementById('getHighPrecisionBtn').addEventListener('click', () => getLocation(true));
    document.getElementById('watchLocationBtn').addEventListener('click', toggleWatchLocation);

    function getLocation(highPrecision = false) {
        const btn = document.getElementById('getLocationBtn');
        const highPrecisionBtn = document.getElementById('getHighPrecisionBtn');
        const errorDiv = document.getElementById('error');
        const successDiv = document.getElementById('success');
        const infoDiv = document.getElementById('locationInfo');

        // 重置显示
        errorDiv.style.display = 'none';
        successDiv.style.display = 'none';
        infoDiv.style.display = 'none';
        btn.disabled = true;
        highPrecisionBtn.disabled = true;

        if (!navigator.geolocation) {
            showError('您的浏览器不支持地理位置服务');
            resetButtons();
            return;
        }

        const options = {
            enableHighAccuracy: highPrecision,    // 高精度模式
            timeout: highPrecision ? 30000 : 15000, // 高精度模式等待更长时间
            maximumAge: highPrecision ? 0 : 60000  // 高精度模式不使用缓存
        };

        console.log(`开始${highPrecision ? '高精度' : '标准'}定位，参数:`, options);

        navigator.geolocation.getCurrentPosition(
            function(position) {
                // 成功获取位置
                displayLocationInfo(position, highPrecision);
                sendToServer(position);
                resetButtons();
            },
            function(error) {
                // 获取位置失败
                handleLocationError(error, highPrecision);
                resetButtons();
            },
            options
        );
    }

    function toggleWatchLocation() {
        const watchBtn = document.getElementById('watchLocationBtn');

        if (watchId === null) {
            // 开始持续监控
            const options = {
                enableHighAccuracy: true,
                timeout: 30000,
                maximumAge: 0
            };

            watchId = navigator.geolocation.watchPosition(
                function(position) {
                    displayLocationInfo(position, true);
                    console.log('持续定位更新:', position);
                },
                function(error) {
                    console.error('持续定位错误:', error);
                },
                options
            );

            watchBtn.textContent = '停止监控';
            watchBtn.style.backgroundColor = '#dc3545';
        } else {
            // 停止监控
            navigator.geolocation.clearWatch(watchId);
            watchId = null;
            watchBtn.textContent = '持续定位监控';
            watchBtn.style.backgroundColor = '#007bff';
        }
    }

    function displayLocationInfo(position, isHighPrecision) {
        const coords = position.coords;
        const timestamp = new Date(position.timestamp).toLocaleString();

        // 判断定位精度等级
        let accuracyLevel = '未知';
        let accuracyClass = '';
        if (coords.accuracy) {
            if (coords.accuracy <= 20) {
                accuracyLevel = '高精度';
                accuracyClass = 'accuracy-high';
            } else if (coords.accuracy <= 100) {
                accuracyLevel = '中等精度';
                accuracyClass = 'accuracy-medium';
            } else {
                accuracyLevel = '低精度';
                accuracyClass = 'accuracy-low';
            }
        }

        // 判断定位来源（基于精度和速度信息）
        let positionSource = '未知';
        if (coords.accuracy <= 50 && coords.speed !== null) {
            positionSource = 'GPS定位';
        } else if (coords.accuracy <= 500) {
            positionSource = 'WiFi/基站定位';
        } else {
            positionSource = 'IP定位';
        }

        // 更新页面显示
        document.getElementById('latitude').textContent = coords.latitude.toFixed(6);
        document.getElementById('longitude').textContent = coords.longitude.toFixed(6);
        document.getElementById('accuracy').textContent = coords.accuracy ? coords.accuracy.toFixed(2) : '未知';
        document.getElementById('altitude').textContent = coords.altitude ? coords.altitude.toFixed(2) : '未知';
        document.getElementById('timestamp').textContent = timestamp;
        document.getElementById('positionSource').textContent = positionSource;

        // 更新精度指示器
        const indicator = document.getElementById('accuracyIndicator');
        indicator.textContent = `${accuracyLevel} (${coords.accuracy ? coords.accuracy.toFixed(0) + '米' : '未知'})`;
        indicator.className = `accuracy-indicator ${accuracyClass}`;

        // 显示位置信息区域
        document.getElementById('locationInfo').style.display = 'block';

        // 显示地图
        showMap(coords.latitude, coords.longitude, coords.accuracy);

        // 显示成功消息
        document.getElementById('success').textContent =
            `定位成功！精度: ${coords.accuracy ? coords.accuracy.toFixed(0) + '米' : '未知'} (${positionSource})`;
        document.getElementById('success').style.display = 'block';

        console.log('定位结果:', {
            latitude: coords.latitude,
            longitude: coords.longitude,
            accuracy: coords.accuracy,
            source: positionSource,
            isHighPrecision: isHighPrecision
        });
    }

    function showMap(lat, lng, accuracy) {
        const mapDiv = document.getElementById('map');

        // 根据精度显示不同缩放级别
        let zoomLevel = 15;
        if (accuracy) {
            if (accuracy > 1000) zoomLevel = 12;
            else if (accuracy > 500) zoomLevel = 13;
            else if (accuracy > 100) zoomLevel = 14;
        }

        // 使用百度地图静态API（无需密钥）
        const mapUrl = `https://api.map.baidu.com/staticimage/v2?center=${lng},${lat}&zoom=${zoomLevel}&width=600&height=300&markers=${lng},${lat}&scale=2`;

        mapDiv.innerHTML = `
            <img src="${mapUrl}" alt="当前位置地图"
                 style="width:100%;height:300px;border-radius:5px;"
                 onerror="this.onerror=null;this.src=''">
            <p style="text-align:center;margin-top:5px;">
                精度: ${accuracy ? accuracy.toFixed(0) + '米' : '未知'} |
                <a href="https://map.baidu.com/@${lat},${lng},${zoomLevel}z" target="_blank">查看详细地图</a>
            </p>
        `;
    }

    function sendToServer(position) {
        const locationData = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy,
            altitude: position.coords.altitude,
            altitudeAccuracy: position.coords.altitudeAccuracy,
            heading: position.coords.heading,
            speed: position.coords.speed,
            timestamp: new Date(position.timestamp).toISOString()
        };

        fetch('/api/location/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(locationData)
        })
            .then(response => response.text())
            .then(data => {
                console.log('位置信息已发送到服务器');
            })
            .catch(error => {
                console.error('发送到服务器失败:', error);
            });
    }

    function handleLocationError(error, isHighPrecision) {
        let message = '';
        switch(error.code) {
            case error.PERMISSION_DENIED:
                message = '用户拒绝了位置访问请求。请检查浏览器位置权限设置。';
                break;
            case error.POSITION_UNAVAILABLE:
                message = isHighPrecision ?
                    '无法获取高精度位置信息。请确保：1) 在室外开阔地带 2) 设备GPS已开启 3) 网络连接正常' :
                    '无法获取当前位置信息';
                break;
            case error.TIMEOUT:
                message = isHighPrecision ?
                    '高精度定位超时。GPS定位需要较长时间，请耐心等待或尝试在更开阔的区域使用。' :
                    '获取位置信息超时';
                break;
            default:
                message = '发生未知错误';
                break;
        }
        showError(message);
    }

    function showError(message) {
        const errorDiv = document.getElementById('error');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    function resetButtons() {
        document.getElementById('getLocationBtn').disabled = false;
        document.getElementById('getHighPrecisionBtn').disabled = false;
        document.getElementById('getLocationBtn').textContent = '标准精度定位';
        document.getElementById('getHighPrecisionBtn').textContent = '高精度定位';
    }

    // 页面加载时检查环境
    window.addEventListener('load', function() {
        if (!navigator.geolocation) {
            showError('您的浏览器不支持地理位置服务，请使用现代浏览器如Chrome、Firefox等');
        }

        // 检查是否为HTTPS环境（高精度定位需要）
        if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
            showError('提示：非HTTPS环境可能影响定位精度，建议在localhost或HTTPS环境下使用高精度定位');
        }
    });
</script>
</body>
</html>
